package org.example.itext;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.security.ExternalSignatureContainer;
import com.itextpdf.text.pdf.security.MakeSignature;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.HashMap;

public class SubMakeSignature extends MakeSignature {
    public static void signExternalContainer(PdfSignatureAppearance sap, ExternalSignatureContainer externalSignatureContainer, int estimatedSize) throws GeneralSecurityException, IOException, DocumentException {
        System.out.println("这是使用自定义方法事项----------------------------------");
        PdfSignature dic = new PdfSignature((PdfName) null, (PdfName) null);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setSignatureCreator(sap.getSignatureCreator());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        externalSignatureContainer.modifySigningDictionary(dic);
        sap.setCryptoDictionary(dic);
        HashMap<PdfName, Integer> exc = new HashMap();
        exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
        sap.preClose(exc);
        byte[] src = sap.getBout();
        int[] range = new int[]{(int) sap.getRange()[0], (int) sap.getRange()[1], (int) sap.getRange()[2], (int) sap.getRange()[3]};
        System.out.println("111111111111======:" + range[0] + "," + range[1] + "," + range[2] + "," + range[3]);
        int length = range[1] + range[3];
        System.out.println("111111111111======length: " + length);
        byte[] byffer1 = new byte[range[1]];
        byte[] buffer2 = new byte[range[3]];
        System.arraycopy(src, 0, byffer1, 0, range[1]);
        System.arraycopy(src, range[2], buffer2, 0, range[3]);
        byte[] dest = new byte[length];
        System.arraycopy(src, 0, dest, 0, range[1]);
        System.arraycopy(src, range[2], dest, range[1], range[3]);
        InputStream data = new ByteArrayInputStream(dest);
        byte[] encodedSig = externalSignatureContainer.sign(data);
        System.out.println("签名后的数据长度1：" + encodedSig.length);
        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, (new PdfString(encodedSig)).setHexWriting(true));
        sap.close(dic2);
    }
}
